package com.mocai.merchant.spring.resolver;

import com.mocai.merchant.core.domain.Wrapper;
import com.mocai.merchant.core.domain.Page;
import com.mocai.merchant.core.domain.RequestWrapper;
import com.mocai.merchant.core.domain.RequestInfo;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 参数解析器
 * 参考：https://www.huangyunkun.com/2014/10/30/spring-mvc-argument-resolver/
 */
public class RequestWrapperParameterResolver implements HandlerMethodArgumentResolver {
    // 分页参数
    private final static String PAGE_NUMBER_KEY = "page.pageNumber";
    private final static String PAGE_SIZE_KEY = "page.pageSize";

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return RequestWrapper.class.isAssignableFrom(parameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        RequestWrapper dto = new RequestWrapper();
        // 所有的请求参数
        Wrapper wrapper = new Wrapper();
        Map<String, String[]> parameterMap = webRequest.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String key = entry.getKey();
            String[] value = entry.getValue();
            // 明确指定数组
            if (key.endsWith("[]")) {
                wrapper.put(key.replace("[]", ""), value);
                continue;
            }
            // 长度为1的参数值，直接拿到第一个元素作为value
            if (value.length == 1) {
                wrapper.put(key, value[0]);
                continue;
            }
            // 正常数组
            wrapper.put(key, value);
        }
        dto.setParameterMap(wrapper);

        // 分页参数信息
        Integer pageNumber = wrapper.getInteger(PAGE_NUMBER_KEY);
        Integer pageSize = wrapper.getInteger(PAGE_SIZE_KEY);
        if (null != pageNumber && null != pageSize) {
            dto.setPage(new Page(pageNumber, pageSize));
        }

        // 抽取请求信息，在Service层使用
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        if (null != request) {
            RequestInfo requestInfo = new RequestInfo();
            requestInfo.setMethod(request.getMethod());
            requestInfo.setContextPath(request.getContextPath());
            requestInfo.setCookies(request.getCookies());
            requestInfo.setRemoteAddr(request.getRemoteAddr());
            dto.setRequestInfo(requestInfo);
        }
        return dto;
    }
}
